<template>
  <div class="buyer">
      <div class="buyeradd">
        <el-button type="primary" @click="addNewButton">+ 新增买家</el-button>

      </div>
      <div class="buyer_search">
        <ul>
          <li><span>国外客户编码</span>
            <el-input  placeholder="请输入国外客户编码" v-model="customerCode"></el-input>
          </li>
          <li><span>公司名称</span>
            <el-input  placeholder="请输入公司名称" v-model="customerName"></el-input>
          </li>
        </ul>
        <el-button type="primary" @click="query">查询</el-button>
      </div>
      <div class="buyer-table">
        <el-table :data="tableData" style="width: 100%" border stripe v-loading="loading">
          <el-table-column prop="customerCode" label="国外客户编码" class-name="customerCode" width="180px">
          </el-table-column>
          <el-table-column prop="customerName" label="公司名称" width="180px">
          </el-table-column>
          <el-table-column prop="customerContacts" label="联系人" min-width="180px">
          </el-table-column>
          <el-table-column prop="customerAddress" label="地址" width="180px">
          </el-table-column>
          <el-table-column prop="customerEmail" label="邮箱" width="180px">
          </el-table-column>
          <el-table-column prop="customerPhone" label="电话" min-width="180px">
          </el-table-column>
          <el-table-column prop="customerFax" label="传真" min-width="180px">
          </el-table-column>
          <el-table-column prop="createTime" label="生成时间" width="180px">
              <template slot-scope="scope">
                 {{_getTime(scope.row.createTime)}}
              </template>
          </el-table-column>
          <el-table-column prop="modifyTime" label="修改时间" width="180px">
              <template slot-scope="scope">
                 {{_getTime(scope.row.modifyTime)}}
              </template>
          </el-table-column>
          <el-table-column prop="credit" label="授信状态" min-width="120px">
            <template slot-scope="scope">
                {{scope.row.credit === 2 ? '黑名单' : (scope.row.credit === 1 ? '白名单' : '')}}
            </template>
          </el-table-column>
          <el-table-column prop="customerMoney" label="授信额度(US)" min-width="180px">
          </el-table-column>
          <el-table-column prop="" label="操作" min-width="180px">
              <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit-outline" @click="revise_table(scope.$index, scope.row)"></el-button>
                  <el-button type="info" icon="el-icon-close" @click="delete_table(scope.$index, scope.row)"></el-button>
              </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currPage"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSize">
          </el-pagination>
        </div>
      </div>
      <!-- 创建和修改卖家 -->
      <el-dialog :visible.sync="dialogFormVisible">
        <el-form :model="dynamicValidateForm" :rules="rules" ref="dynamicValidateForm" label-width="120px" label-position="right">
          <el-form-item label="国外客户编码" prop="customerCode" :show-message="showMessage">
            <el-input v-model="dynamicValidateForm.customerCode" :disabled="disabling"></el-input>
          </el-form-item>
          <el-form-item label="公司名称" prop="customerName" :show-message="showMessage">
            <el-input v-model="dynamicValidateForm.customerName" :disabled="false"></el-input>
          </el-form-item>
          <el-form-item label="公司简写" prop="customerAbbreviation" :show-message="showMessage">
            <el-input v-model="dynamicValidateForm.customerAbbreviation" :disabled="false"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="customerAddress">
            <el-input v-model="dynamicValidateForm.customerAddress"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="customerEmail">
            <el-input v-model="dynamicValidateForm.customerEmail"></el-input>
          </el-form-item>
          <!-- <el-form-item label="联系人" v-for="item in dynamicValidateForm.customerContacts" prop="customerContacts">
            <el-input v-model="item.name"></el-input>
          </el-form-item> -->
          <el-form-item label="联系人" prop="customerContacts">
            <el-input v-model="dynamicValidateForm.customerContacts"></el-input>
          </el-form-item>
          <!-- <div class="add-customerContacts">
            <i class="el-icon-circle-plus" @click="addcustomerContacts"></i>
            <i class="el-icon-remove" v-show="dynamicValidateForm.customerContacts.length>1" @click="selcustomerContacts"></i>
          </div> -->
          <el-form-item label="联系电话" prop="customerPhone">
            <el-input v-model="dynamicValidateForm.customerPhone"></el-input>
          </el-form-item>
          <!-- <el-form-item label="电话" v-for="item in dynamicValidateForm.customerPhone" prop="customerPhone">
            <el-input v-model="item.phone"></el-input>
          </el-form-item> -->
          <!-- <div class="add-phoneNumber">
              <i class="el-icon-circle-plus" @click="addPhoneNumber"></i>
              <i class="el-icon-remove" v-show="dynamicValidateForm.customerPhone.length>1" @click="selPhoneNumber"></i>
          </div> -->
          <el-form-item label="传真" prop="customerFax">
            <el-input v-model="dynamicValidateForm.customerFax"></el-input>
          </el-form-item>
          <el-form-item label="附件">
              <el-upload
                class="upload-demo"
                action="/api/common/upload"
                :on-success="actionSuccess"
                :on-change="handleChange"
                :file-list="fileList"
                :on-preview="fileDown"
                :on-remove="onRemove"
                >
                <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="dynamicValidateForm.customerRemarks"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
           <el-button type="primary" @click="submitForm()">提交</el-button>
           <el-button @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 是否删除 -->
      <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="30%">
          <span>确定删除吗？</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="delete_sure">确 定</el-button>
          </span>
        </el-dialog>
  </div>
</template>
<script>
import {getMessage, addNew, deleteSure, getUpdata, filedownload, deleteFile} from '@/server/customermanagement/index.js'
import {getOrderNumber} from '@/server/initiatingprocess'

export default {
  data(){
    //   表单验证规则
    //   公司简写规则
      let customerAbbreviation_rule = (rule, value, callback) => {
        if(!value){
            return callback(new Error('请输入公司简写'));
        }
        if (value.length > 10) {
            return callback(new Error('请输入小于10个字符'));
        }
        let str = /^[A-Za-z]+$/;
        if (!str.test(value)) {
            return callback(new Error('只能由字母组成'));
        }
      };
    //   公司名称规则
      let customerName_rule = (rule, value, callback) => {
          if(!value){
              return callback(new Error('请输入公司名称'));
          }
      };
    //   国外客户编码规则
      let customerCode_rule = (rule, value, callback) => {
          if(!value){
              return callback(new Error('请输入国外客户编码'));
          }
      };
    //   地址规则
      let customerAddress_rule = (rule, value, callback) => {
          if(!value){
              return callback(new Error('请输入地址'));
          }
      };
    //   邮箱规则
      let email_rule = (rule, value, callback) => {
          let str = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
          if(!str.test(value)){
              return callback(new Error('请输入正确的邮箱格式'));
          }
      };
    //   联系人规则
      let customerContacts_rule = (rule, value, callback) => {
          // let name = value[value.length - 1].name
          let str = /^.*[~!@#\$%\^&\*\(\)_+\-=\[\]\{\}\\\|\'\";:,\<\.\>\/\?\s+].*$/;
          if(str.test(value)){
              return callback(new Error('输入联系人错误'));
          };
          let num = /[0-9]/;
          if(num.test(value)){
              return callback(new Error('输入联系人错误'));
          };
          if(!value){
              return callback(new Error('输入联系人错误'));
          };
          // this.addcustomerContactsFlag = true;
      };
    //   联系电话规则
        let customerPhone_rule = (rule, value, callback) => {
            // let name = value[value.length - 1].phone
            let str = /^.*[~!@#\$%\^&\*\(\)_+\-=\[\]\{\}\\\|\'\";:,\<\.\>\/\?\s+].*$/;
            if(str.test(value)){
                return callback(new Error('输入联系电话错误'));
            };
            let num = /[A-Za-z]/;
            if(num.test(value)){
                return callback(new Error('输入联系电话错误'));
            };
            if(!value){
                return callback(new Error('输入联系电话错误'));
            };
            // this.addPhoneNumberFlag = true;
        };
        //   传真规则
        let customerFax_rule = (rule, value, callback) => {
            let str = /^.*[~!@#\$%\^&\*\(\)_+\=\[\]\{\}\\\|\'\";:,\<\.\>\/\?\s+].*$/;
            if(str.test(value)){
                return callback(new Error('输入传真错误'));
            };
            let num = /[A-Za-z]/;
            if(num.test(value)){
                return callback(new Error('输入传真错误'));
            };
            if(!value){
                return callback(new Error('输入传真错误'));
            };
            // this.addPhoneNumberFlag = true;
        };
      return {
        disabling: false,//设置只读
        type: 1,//选择tab标签页
        id: '',//当前需要删除行的id
        userMessage: '',//当前登录用户信息
        showMessage: true,//是否展示错误信息
        customerCode: '',//外国客户编码
        _customerCode: '',//外国客户编码
        customerName: '',//公司名称
        _customerName: '',//公司名称
        loading: false,//加载中
        submitwithForm: 'dynamicValidateForm',//打开form表单弹窗判断用
        row: '',//当前行信息
        _mSG:{},//保存当前行内容
        addcustomerContactsFlag: false,//是否可新增联系人
        addPhoneNumberFlag: false,//是否可新增联系电话
        tableData: [],//表格数据
        dialogVisible: false,//表格确定删除弹出框显示隐藏
        dialogFormVisible: false,//新增买家弹出框是否显示
        fileList: [],//上传文件数据
        currPage: 1,//默认当前页数
        pageSize: 30,//默认当前页大小
        totalSize: 0,//总数据条数
        _deleteRow: '',//删除行暂存
        dynamicValidateForm: {//表单数据
            type: 1,
            customerCode: '',//国外客户编码
            customerName: '',//公司名称
            customerAbbreviation: '',//公司简写
            customerEmail: '',//邮箱
            customerContacts: '',//联系人
            customerAddress: '',//地址
            customerPhone: '',//联系电话
            fileList:'',//附件
            customerFax: '',//传真
            customerRemarks: ''//备注
        },
        rules: {//表单校验规则
            customerCode: [
                { validator: customerCode_rule, required: true, trigger: 'blur' },
            ],
            customerName: [
                { validator: customerName_rule, required: true, trigger: 'blur' }
            ],
            customerAbbreviation: [
                { validator: customerAbbreviation_rule, required: true, trigger: 'blur' }
            ],
            customerAddress: [
                { validator: customerAddress_rule, required: true, trigger: 'blur' }
            ],
            customerEmail: [
                { validator: email_rule, required: true, trigger: 'blur' },
            ],
            customerContacts: [
                { validator: customerContacts_rule, required: true, trigger: 'blur' },
            ],
            customerPhone: [
                { validator: customerPhone_rule, required: true, trigger: 'blur' },
            ],
            customerFax: [
                { validator: customerFax_rule, required: true, trigger: 'blur' },
            ],
        },
      }
  },
  mounted() {
    //获取当前权限
    this.userMessage = JSON.parse(localStorage.getItem("userMsg"));
    this.query();
  },
  methods: {
    //   点击查询查询表格
      query(){
          this.currPage = 1;
          this.pageSize = 30;
          this._customerCode = this.customerCode;
          this._customerName = this.customerName;
        let obj = {
            type: this.type,
            customerCode: this.customerCode,
            customerName: this.customerName,
            currPage: 0,
            pageSize: this.pageSize
        };

        this._mSG = obj;
        this.getMsg(obj);
      },
      getMsg(obj){
          this.loading = true;
          getMessage(obj).then((res)=>{
              try {
                  if(res.code === 1){
                      this.totalSize = res.data.totalSize
                      this.tableData = res.data.datas
                  }else{
                      this.$message.error('查询失败，请检查网络后重试');
                  }
              } catch (e) {
                  this.$message.error('查询失败，请检查网络后重试');
              }
              this.loading = false;
          })
      },
    //   新增联系人
      // addcustomerContacts(){
      //     if(!this.addcustomerContactsFlag){
      //         if(this.dynamicValidateForm.customerContacts.length > 1){
      //             let num = this.$refs['dynamicValidateForm'].$children.length-1;
      //             this.$refs['dynamicValidateForm'].$children[num].validateMessage = "输入联系人错误"
      //             this.$refs['dynamicValidateForm'].$children[num].validateState = "error"
      //         }else{
      //              this.$refs['dynamicValidateForm'].validateField('customerContacts');
      //         }
      //         return
      //     }
      //     this.dynamicValidateForm.customerContacts.push({
      //         name: ""
      //     });
      //     this.addcustomerContactsFlag = false;
      // },
    //   去掉联系人
      // selcustomerContacts(){
      //     this.dynamicValidateForm.customerContacts.pop();
      // },
    //   新增电话号
      // addPhoneNumber(){
      //     if(!this.addPhoneNumberFlag){
      //         if(this.dynamicValidateForm.customerPhone.length > 1){
      //             let num = this.$refs['dynamicValidateForm'].$children.length-1;
      //             this.$refs['dynamicValidateForm'].$children[num].validateMessage = "输入联系号码错误"
      //             this.$refs['dynamicValidateForm'].$children[num].validateState = "error"
      //         }else{
      //              this.$refs['dynamicValidateForm'].validateField('customerPhone');
      //         }
      //         return
      //     }
      //     this.dynamicValidateForm.customerPhone.push({
      //         phone: ""
      //     });
      //     this.addPhoneNumberFlag = false;
      // },
    //   删除电话号
      // selPhoneNumber(){
      //     this.dynamicValidateForm.customerPhone.pop();
      // },
    //   上传列表
      handleChange(file, fileList){

      },

      // 下载文件
      fileDown(file) {
        window.open('http://47.104.93.41/api/common/download?id='+file.id)
      },
      // 附件删除时
      onRemove(file, fileList) {
        deleteFile({'id':file.id}).then((res) => {
            if(res.code === 1){
                this.fileList = fileList;
                this.dynamicValidateForm.fileList = '';
            }else{
                this.$message.error('删除失败，请检查网络后重试');
            }
        })
      },
      // 附件添加时
      actionSuccess(response, file, fileList){
          this.dynamicValidateForm.fileList = '';
          let x = response.data.datas[0];
          x.name = response.data.datas[0].fileName;
          this.fileList.push(x);
      },
    //   点击新增买家button
      addNewButton(){
          this.disabling = false;
          this.showMessage = true;
          this.fileList = [];
        this.dynamicValidateForm = {//表单数据
            type: 1,
            credit: 0,
            customerCode: '',//国外客户编码
            customerName: '',//公司名称
            customerAbbreviation: '',//公司简写
            customerEmail: '',//邮箱
            customerContacts: '',//联系人
            customerAddress: '',//地址
            customerPhone: '',//联系电话
            fileList:'',//附件
            customerFax: '',//chuanzhen
            customerRemarks: ''//备注
        };
        this.getOrderNumberFn();
        this.dialogFormVisible = true
      },
      //随机客户编码
      getOrderNumberFn() {

        let yearStr = new Date().getFullYear();
        let obj = {
          year: yearStr
        };
        getOrderNumber(obj).then((res) => {
            try {
                this.dynamicValidateForm.customerCode = `B${yearStr}${res}`;
            } catch (e) {
                this.$message.error('获取客户编码有误');
            }
        });
      },
    //   新增买家确认
      submitForm() {
        let obj = this.dynamicValidateForm;
        // 手动触发验证
        this.$refs['dynamicValidateForm'].validate((valid) => {
            if (valid) {
              console.log('submit!');
            } else {
              console.log('error submit!!');
              return false;
            }
        });
        // this.$refs['dynamicValidateForm'].validateField('customerCode');
        // this.$refs['dynamicValidateForm'].validateField('customerName');
        // this.$refs['dynamicValidateForm'].validateField('customerAbbreviation');
        // this.$refs['dynamicValidateForm'].validateField('customerEmail');
        // this.$refs['dynamicValidateForm'].validateField('customerAddress');
        if(obj.customerCode == '' || obj.customerName == '' || obj.customerAbbreviation == '' || obj.customerAddress == '' || obj.customerAbbreviation.length >= 10 || obj.customerContacts === '' || obj.customerPhone === '' ){
          return
        }else{
          // obj.customerContacts = this._joinString(this.dynamicValidateForm.customerContacts);
          // obj.customerPhone = this._joinString(this.dynamicValidateForm.customerPhone);
          try {
              for(let i = 0 ; i < this.fileList.length ; i++){
                  obj.fileList += this.fileList[i].id + ','
              }
              let x = obj.fileList.length
              obj.fileList = obj.fileList.slice(0, x - 1);
          } catch (e) {
              obj.fileList = ''
          }
          try {
              delete obj.createTime
              delete obj.modifyTime
          } catch (e) {

          }
          addNew(obj).then((res) => {
              try {
                  if(res.code === 1){
                      this.$message({
                       message: '提交成功',
                       type: 'success'
                     });
                     this.dialogFormVisible = false;
                  }else{
                      // this.$message.error('提交失败');
                      this.$message.error(res.message);
                      this.dialogFormVisible = true;
                  }
              } catch (e) {
                  this.$message.error('提交错误，请检查网络后重试');
                  this.dialogFormVisible = false;
              }
          }).then((res)=>{
              this.getMsg(this._mSG);
          }).catch((err) => {
              this.dialogFormVisible = false;
          });
        }
      },
    //    点击查询
      revise_table(index, row) {
          this.disabling = true;
          this.showMessage = false;
          let obj = {
              'type': 1,
              'customerCode': row.customerCode,
              'customerName': row.customerName,
              'customerContacts': row.customerContacts,
              'customerAddress': row.customerAddress,
              'customerEmail': row.customerEmail,
              'customerPhone': row.customerPhone,
              'createTime': row.createTime,
              'modifyTime': row.modifyTime,
              'customerFax': row.customerFax,
          };
          let obj2 = {
            'type': 1,
            'customerId': row.id,
            'status': 1
          };
          this.row = obj;
          getMessage(obj).then((res)=>{
              try {
                  if(res.code === 1){
                      let _obj = res.data.datas[0];
                      // _obj.customerContacts=this._makeObj(res.data.datas[0].customerContacts, 'name');
                      // _obj.customerPhone=this._makeObj(res.data.datas[0].customerPhone, 'phone');
                      this.dynamicValidateForm = _obj;
                      this.dynamicValidateForm.fileList = '';
                      this.dialogFormVisible = true;
                  }else{
                      this.$message.error('查询失败，请检查网络后重试');
                  }
              } catch (e) {
                this.$message.error('查询失败，请检查网络后重试');
              }
          });
          getUpdata(obj2).then((res)=>{
              try {
                  if(res.code === 1){
                      this.dynamicValidateForm.fileList = '';
                      this.fileList = res.data.datas;
                      for(let i = 0 ; i < res.data.datas.length ; i++){
                          this.fileList[i].name = res.data.datas[i].fileName
                      }
                  }else{
                      return
                  }
              } catch (e) {
                return
              }
          })
      },
    //   点击删除表格按钮
      delete_table(index, row) {
        this.id = row.id;
        this._deleteRow = index;
        this.dialogVisible = true;
      },
    //   点击确定删除
      delete_sure() {
        let id = {
            'id': this.id
        };
        deleteSure(id).then((res)=>{
            if(res.code === 1){
                this.tableData.splice(this._deleteRow, 1);
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
            }else{
                this.$message.error('删除失败，请检查网络后重试');
            }
        });
        this.dialogVisible = false;
    },
    // 分页每页多少条
    handleSizeChange(val) {
        this.pageSize = val;
        let obj = {
            type: this.type,
            customerCode: this._customerCode,
            customerName: this._customerName,
            currPage: 0,
            pageSize: this.pageSize
        };
        this.getMsg(obj);
    },
    // 分页当前页
    handleCurrentChange(val) {
        this.currPage = val;
        let obj = {
            type: this.type,
            customerCode: this._customerCode,
            customerName: this._customerName,
            currPage: val - 1,
            pageSize: this.pageSize
        };
        this.getMsg(obj);
    },
    // 将数组对象转化为字符串
    _joinString(arr) {
        let str = '';
        for(let i = 0 ; i < arr.length ; i++) {
            if(arr[i].name == undefined){
                str += arr[i].phone + ','
            }else{
                str += arr[i].name + ','
            }
        };
        str = str.slice(0, str.length - 1);
        return str
    },
    // 将字符串转化为数组对象
    _makeObj(str, name) {
        let arr = str.split(','),
            arrReturn = [];
        for(let i = 0 ; i < arr.length ; i++) {
            if(name == 'name'){
                arrReturn.push({
                  'name': arr[i]
                })
            }else{
                arrReturn.push({
                  'phone': arr[i]
                })
            }
        };
        return arrReturn
    },
    // 将时间戳转化为时间字符串
    _getTime(x){
        if(x === null || x === undefined || x === ''){
            return '-'
        }
        let time = new Date(x);
        return time.getFullYear() + '/' + (time.getMonth() + 1) + '/' + time.getDate();
    },
  }
}
</script>
<style lang="sass" scoped>
@import "../../assets/css/common.sass"
.buyer
  width: 100%
  padding: 20px
  border: 1px solid #e6ebf5
  border-top: none
  box-sizing: border-box
  border-radius: 0 0 4px 4px
.buyer_search
  margin-top: 20px
  width: 100%
  border: 1px solid #e6ebf5
  border-radius: 4px
  padding: 20px
  padding-bottom: 10px
  box-sizing: border-box
  &:after
    @include clear
  ul
    width: 90%
    float: left
    &:after
      @include clear
    li
      width: 40%
      height: 40px
      line-height: 40px
      float: left
      padding-right: 10px
      box-sizing: border-box
      margin-bottom: 10px
      span
        font-size: 14px
        display: inline-block
        width: 90px
      .el-input, .el-select,
        width: 60%
      .block
        width: 60%
        display: inline-block
        div
          width: 100%
          border: 1px solid #d8dce5
  .el-button
    width: 10%
    height: 40px
.buyer-table
  box-sizing: border-box
  // border: 1px solid #e6ebf5
  border-radius: 4px
  margin-top: 20px
  border-right: none
  .el-table
    border-radius: 4px
  .el-button
    height: 30px
    line-height: 7px
.el-form-item
  margin-bottom: 20px
  .el-input, .el-textarea, .upload-demo
    width: 95%
.el-dialog__body
  padding-left: 30px

.add-customerContacts, .add-phoneNumber
  margin-bottom: 20px
  width: 100%
  padding-left: 120px
  box-sizing: border-box
  .el-icon-circle-plus, .el-icon-remove
    font-size: 30px
    cursor: pointer
.block
  width: 100%
  margin-top: 20px
  margin-bottom: 20px
  text-align: center
</style>
